package com.imax.center.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.imax.center.common.Result;
import com.imax.center.common.ResultCode;
import com.imax.center.constant.H3yunApiConstants;
import com.imax.center.domain.HomeCameraDomain;
import com.imax.center.domain.UpdateCameraOrderDomain;
import com.imax.center.model.EzvizChannel;
import com.imax.center.model.EzvizDevice;
import com.imax.center.service.CommonService;
import com.imax.center.service.H3yunService;
import com.imax.center.service.impl.h3yun.H3yunOperate;
import com.imax.center.service.impl.h3yun.BizHandler;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.DateUtil;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.imax.center.service.DataCacheService;

import java.util.*;

@Slf4j
@Service
public class H3yunServiceImpl implements H3yunService {

    @Autowired
    H3yunOperate h3yunOperate;

    @Autowired
    DataCacheService dataCacheService;

    @Autowired
    CommonService commonService;

    @Override
    public Result<JSONArray> getVipLevels() {
        JSONArray bizObjectArray = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_VIP_LEVEL, new HashMap<>());
        return Result.success(bizObjectArray, "获取VIP等级列表成功");
    }
    
    @Override
    public Result<JSONObject> createVipLevel(String levelName, String levelRemark) {
        // 构建业务对象数据
        JSONObject bizObject = new JSONObject();
        bizObject.put("LevelName", levelName);
        bizObject.put("LevelRemark", levelRemark);
        JSONObject returnData = h3yunOperate.CreateBizObject(H3yunApiConstants.SCHEMA_VIP_LEVEL, bizObject);
        return Result.success(returnData, "创建VIP等级成功");
    }
    
    @Override
    public Result<JSONObject> saveDeviceInfo(EzvizDevice device) {
        // 构建业务对象数据
        JSONObject bizObject = new JSONObject();
        bizObject.put("DeviceId", device.getId());
        bizObject.put("DeviceSerial", device.getDeviceSerial());
        bizObject.put("DeviceName", device.getDeviceName());
        bizObject.put("DeviceType", device.getDeviceType());
        bizObject.put("DeviceStatus", device.getStatus());
        bizObject.put("Defence", device.getDefence());
        bizObject.put("DeviceVersion", device.getDeviceVersion());
        bizObject.put("AddTime", device.getAddTime());
        bizObject.put("UpdateTime", device.getUpdateTime());
        bizObject.put("ParentCategory", device.getParentCategory());
        bizObject.put("RiskLevel", device.getRiskLevel());
        bizObject.put("NetAddress", device.getNetAddress());
        JSONObject returnData = h3yunOperate.CreateBizObject(H3yunApiConstants.SCHEMA_DEVICE_INFO, bizObject);
        return Result.success(returnData, "保存设备信息成功");
    }
    
    @Override
    public Result<JSONArray> batchSaveDeviceInfo(List<EzvizDevice> devices) {
        List<JSONObject> successResults = new ArrayList<>();
        List<String> errorMessages = new ArrayList<>();
        
        for (EzvizDevice device : devices) {
            // 先检查设备是否已存在
            Map<String, Object> queryParams = new HashMap<>();
            queryParams.put("DeviceId", device.getId());
            Result<JSONArray> queryResult = queryDeviceInfo(queryParams);
            
            // 只有当设备不存在时才进行保存
            if (queryResult.getData() == null || queryResult.getData().isEmpty()) {
                Result<JSONObject> result = saveDeviceInfo(device);
                if (Objects.equals(result.getCode(), ResultCode.SUCCESS.getCode())) {
                    successResults.add(result.getData());
                } else {
                    errorMessages.add(String.format("设备[%s]保存失败: %s", device.getDeviceSerial(), result.getMsg()));
                }
            } else {
                log.info("设备[{}]已存在，更新", device.getDeviceSerial());
                //更新设备名称
                JSONObject updateObject = new JSONObject();
                String objectId = queryResult.getData().getJSONObject(0).getString("ObjectId");
                updateObject.put("DeviceName", device.getDeviceName());
                h3yunOperate.UpdateBizObject(H3yunApiConstants.SCHEMA_DEVICE_INFO, objectId, updateObject);
            }
        }
        
        if (errorMessages.isEmpty()) {
            JSONArray resultArray = new JSONArray();
            resultArray.addAll(successResults);
            return Result.success(resultArray, "批量保存设备信息成功");
        } else {
            log.error("批量保存设备信息部分失败: {}", String.join("; ", errorMessages));
            if (!successResults.isEmpty()) {
                JSONArray resultArray = new JSONArray();
                resultArray.addAll(successResults);
                return Result.success(resultArray, "批量保存设备信息部分成功，部分失败: " + String.join("; ", errorMessages));
            } else {
                return Result.error(ResultCode.SYSTEM_ERROR, "批量保存设备信息全部失败: " + String.join("; ", errorMessages));
            }
        }
    }

    @Override
    public Result<JSONObject> saveChannelInfo(EzvizChannel device) {
        // 构建业务对象数据
        JSONObject bizObject = new JSONObject();
        bizObject.put("ChannelId", device.getId());
        bizObject.put("DeviceSerial", device.getDeviceSerial());
        bizObject.put("ChannelNo", device.getChannelNo());
        bizObject.put("ChannelName", device.getChannelName());
        bizObject.put("ChannelStatus", device.getStatus());
        bizObject.put("IsShared", device.getIsShared());
        bizObject.put("PicUrl", device.getPicUrl());
        bizObject.put("IsEncrypt", device.getIsEncrypt());
        bizObject.put("VideoLevel", device.getVideoLevel());
        bizObject.put("Permission", device.getPermission());
        bizObject.put("IsAdd", device.getIsAdd());
        JSONObject returnData = h3yunOperate.CreateBizObject(H3yunApiConstants.SCHEMA_CHANNEL_INFO, bizObject);
        return Result.success(returnData, "保存通道信息成功");
    }

    @Override
    public Result<JSONArray> batchSaveChannelInfo(List<EzvizChannel> devices) {
        List<JSONObject> successResults = new ArrayList<>();
        List<String> errorMessages = new ArrayList<>();

        for (EzvizChannel device : devices) {
            //如果isShared字段为0，表示未关联，不需要同步
            if (device.getIsShared() == null || Objects.equals(device.getIsShared(), "0")) {
                log.info("通道[{}]-设备[{}]未关联，跳过保存", device.getChannelNo(), device.getDeviceSerial());
                continue;
            }
            //如果通过名称中包含@，不需要同步
            if (device.getChannelName().contains("@")) {
                log.info("通道[{}]-设备[{}]名称中包含@，跳过保存", device.getChannelNo(), device.getDeviceSerial());
                continue;
            }
            // 先检查通道是否已存在
            Map<String, Object> queryParams = new HashMap<>();
            queryParams.put("ChannelId", device.getId());
            Result<JSONArray> queryResult = queryChannelInfo(queryParams, "admin", null);

            // 只有当通道不存在时才进行保存
            if (queryResult.getData() == null || queryResult.getData().isEmpty()) {
                Result<JSONObject> result = saveChannelInfo(device);
                if (Objects.equals(result.getCode(), ResultCode.SUCCESS.getCode())) {
                    successResults.add(result.getData());
                } else {
                    errorMessages.add(String.format("通道[%s]保存失败: %s", device.getChannelNo(), result.getMsg()));
                }
            } else {
                log.info("设备[{}]-通道[{}]已存在，更新", device.getDeviceSerial(), device.getChannelNo());
                //更新通道名称
                JSONObject updateObject = new JSONObject();
                String objectId = queryResult.getData().getJSONObject(0).getString("ObjectId");
                updateObject.put("ChannelName", device.getChannelName());
                h3yunOperate.UpdateBizObject(H3yunApiConstants.SCHEMA_CHANNEL_INFO, objectId, updateObject);
            }
        }

        if (errorMessages.isEmpty()) {
            JSONArray resultArray = new JSONArray();
            resultArray.addAll(successResults);
            return Result.success(resultArray, "批量保存通道信息成功");
        } else {
            log.error("批量保存通道信息部分失败: {}", String.join("; ", errorMessages));
            if (!successResults.isEmpty()) {
                JSONArray resultArray = new JSONArray();
                resultArray.addAll(successResults);
                return Result.success(resultArray, "批量保存通道信息部分成功，部分失败: " + String.join("; ", errorMessages));
            } else {
                return Result.error(ResultCode.SYSTEM_ERROR, "批量保存通道信息全部失败: " + String.join("; ", errorMessages));
            }
        }
    }
    
    @Override
    public Result<JSONArray> queryDeviceInfo(Map<String, Object> queryParams) {
        JSONArray bizObjectArray = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_DEVICE_INFO, queryParams);
        return Result.success(bizObjectArray, "查询设备信息成功");
    }

    @Override
    public Result<JSONArray> queryChildrenOrgList(String ObjectId, String powerCode, String orgObjectId) {
        // 查询客户信息列表，无需查询参数
        Map<String, Object> queryParams = new HashMap<>();
        if (ObjectId != null && !ObjectId.isEmpty()) {
            queryParams.put("ObjectId", ObjectId);
        }
        String ReturnItems = "ObjectId, Name, ParentOrg, ClientName, Address, Location, IsFenYuan";
        JSONArray bizObjectArray = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_CHILDREN_ORG, queryParams, ReturnItems);

        //如果powerCode为admin，则返回全部数据，否则查询指定区域
        JSONArray list = new JSONArray();
        if (Objects.equals(powerCode, "admin")) {
            list.addAll(bizObjectArray);
        } else {
            for (int i = 0; i < bizObjectArray.size(); i++) {
                JSONObject obj = bizObjectArray.getJSONObject(i);
                if (obj.containsKey("ObjectId") && obj.getString("ObjectId").equals(orgObjectId)) {
                    list.add(obj);
                }
            }
        }

        //解析Address和Location字段
        this.parseOrgAddress(list);

        return Result.success(list, "查询客户信息列表成功");
    }

    private JSONArray queryFenYuanOrgList() {
        // 查询客户信息列表，无需查询参数
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("IsFenYuan", true);
        String ReturnItems = "ObjectId, Name, ParentOrg, ClientName, Address, Location, IsFenYuan";
        JSONArray list = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_CHILDREN_ORG, queryParams, ReturnItems);

        //解析Address和Location字段
        this.parseOrgAddress(list);

        return list;
    }

    private void parseOrgAddress(JSONArray list) {
        // 解析Address和Location字段
        if (!list.isEmpty()) {
            for (int i = 0; i < list.size(); i++) {
                JSONObject item = list.getJSONObject(i);

                // 解析Address字段
                if (item.containsKey("Address") && item.getString("Address") != null) {
                    try {
                        String addressStr = item.getString("Address");
                        JSONObject addressObj = JSONObject.parseObject(addressStr);
                        if (addressObj != null) {
                            item.put("AdCode", addressObj.getString("adcode"));
                            item.put("AdName", addressObj.getString("adname"));
                        }
                    } catch (Exception e) {
                        log.error("解析Address字段失败: {}", e.getMessage());
                    }
                }

                // 解析Location字段
                if (item.containsKey("Location") && item.getString("Location") != null) {
                    try {
                        String locationStr = item.getString("Location");
                        JSONObject locationObj = JSONObject.parseObject(locationStr);

                        if (locationObj != null) {
                            item.put("DetailAddress", locationObj.getString("Address"));
                            JSONObject point = locationObj.getJSONObject("Point");
                            if (point != null) {
                                item.put("Lat", point.getDouble("lat"));
                                item.put("Lng", point.getDouble("lng"));
                            }
                        }
                    } catch (Exception e) {
                        log.error("解析Location字段失败: {}", e.getMessage());
                    }
                }
            }
        }
    }

    @Override
    public Result<JSONObject> queryRegionTree(String parentCode) {
        Map<String, Object> queryName = new HashMap<>();
        queryName.put("AreaCode", parentCode);
        JSONArray currentArray = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_REGION_AREA, queryName, "*");
        if (currentArray == null || currentArray.isEmpty()) {
            return Result.error(ResultCode.PARAM_ERROR, "未找到指定parentCode的行政区划信息");
        }
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("FullName", currentArray.getJSONObject(0).getString("AreaName"));
        String ReturnItems = "AreaCode, AreaName, ParentCode, CityLevel, Lng, Lat";
        JSONArray bizObjectArray = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_REGION_AREA, queryParams, ReturnItems, true, 8);

        // 将平面数组转换为树形结构，使用BizHandler中的方法
        JSONObject rootNode = BizHandler.buildRegionTree(bizObjectArray, parentCode);
        
        return Result.success(rootNode, "查询成功");
    }

    @Override
    public Result<JSONObject> getPowerRegionTree(String powerCode, String orgObjectId) {
        String parentCode = "100000";
        // 尝试从缓存中获取区域数据
        JSONArray bizObjectArray = dataCacheService.getRegionData();
        //如果powerCode为admin，则orgObjectId为null，表示查询所有区域，否则查询指定区域
        if (Objects.equals(powerCode, "admin")) {
            orgObjectId = null;
        }
        Result<JSONArray> jsonArrayResult = this.queryChildrenOrgList(orgObjectId, "admin", null);
        JSONArray childrenOrgList = jsonArrayResult.getData();
        // 异常处理
        if (childrenOrgList == null || childrenOrgList.isEmpty()) {
            return Result.error(ResultCode.PARAM_ERROR, "未找到客户信息列表");
        }
        
        // 创建一个List存储映射后的对象
        List<JSONObject> mappedOrgList = new ArrayList<>();
        
        try {
            for (int i = 0; i < childrenOrgList.size(); i++) {
                JSONObject orgItem = childrenOrgList.getJSONObject(i);
                String adCode = orgItem.getString("AdCode");
                // adCode判空
                if (adCode == null || adCode.equals("")) {
                    continue;
                }

                //如果IsFenYuan为true，则从childrenOrgList中找到其父节点
                if (orgItem.getBoolean("IsFenYuan")) {
                    for (int j = 0; j < childrenOrgList.size(); j++) {
                        JSONObject parentItem = childrenOrgList.getJSONObject(j);
                        if (parentItem.getString("ObjectId").equals(orgItem.getString("ParentOrg"))) {
                            adCode = parentItem.getString("ObjectId");
                        }
                    }
                }

                // 字段映射 ClientName -> AreaName AdCode -> AreaCode CityLevel默认为4 Lng->Lng Lat->Lat
                // 新创建一个对象
                JSONObject newOrgItem = new JSONObject();
                newOrgItem.put("AreaName", orgItem.getString("ClientName"));
                newOrgItem.put("AreaCode", orgItem.getString("ObjectId"));
                newOrgItem.put("ParentCode", adCode);
                newOrgItem.put("CityLevel", 4);
                newOrgItem.put("Lng", orgItem.getDouble("Lng"));
                newOrgItem.put("Lat", orgItem.getDouble("Lat"));
                
                // 添加到映射列表中
                mappedOrgList.add(newOrgItem);
            }
            
            // 存储所有需要添加到树中的节点
            List<JSONObject> allNodes = new ArrayList<>();
            
            for (JSONObject mappedOrg : mappedOrgList) {
                // 查找并添加父级路径
                List<JSONObject> parentPath = findParentCodePath(mappedOrg.getString("ParentCode"), bizObjectArray);
                allNodes.addAll(parentPath);
                // 添加组织本身
                allNodes.add(mappedOrg);
            }
            
            // 去重，避免重复节点
            Map<String, JSONObject> uniqueNodes = new HashMap<>();
            for (JSONObject node : allNodes) {
                uniqueNodes.put(node.getString("AreaCode"), node);
            }
            
            // 创建新的JSONArray
            JSONArray resultArray = new JSONArray();
            resultArray.addAll(uniqueNodes.values());
            
            // 将平面数组转换为树形结构，使用BizHandler中的方法
            JSONObject rootNode = BizHandler.buildRegionTree(resultArray, parentCode);
            return Result.success(rootNode, "查询成功");
            
        } catch (Exception e) {
            log.error("列表失败: {}", e.getMessage());
            return Result.error(ResultCode.SYSTEM_ERROR, "失败: " + e.getMessage());
        }
    }

    @Override
    public Result<JSONObject> getPowerOrgTree(String powerCode, String orgObjectId) {
        String parentCode = "0";
        int CityLevel = 2;
        //如果powerCode为admin，则orgObjectId为null，表示查询所有区域，否则查询指定区域
        if (Objects.equals(powerCode, "admin")) {
            orgObjectId = null;
        }
        Result<JSONArray> jsonArrayResult = this.queryChildrenOrgList(orgObjectId, "admin", null);
        JSONArray fenYuanList = this.queryFenYuanOrgList();
        JSONArray childrenOrgList = jsonArrayResult.getData();
        List<String> childrenOrgParentIds = new ArrayList<>();
        // 收集所有子组织的父级ID
        for (int i = 0; i < childrenOrgList.size(); i++) {
            JSONObject orgItem = childrenOrgList.getJSONObject(i);
            childrenOrgParentIds.add(orgItem.getString("ObjectId"));
        }
        //如果fenYuanList的数据在childrenOrgParentIds中才添加到其中
        for (int i = 0; i < fenYuanList.size(); i++) {
            JSONObject fenYuanItem = fenYuanList.getJSONObject(i);
            if (childrenOrgParentIds.contains(fenYuanItem.getString("ParentOrg"))) {
                childrenOrgList.add(fenYuanItem);
            }
        }
        // 异常处理
        if (childrenOrgList == null || childrenOrgList.isEmpty()) {
            return Result.error(ResultCode.PARAM_ERROR, "未找到客户信息列表");
        }

        // 创建一个List存储映射后的对象
        List<JSONObject> mappedOrgList = new ArrayList<>();

        try {
            for (int i = 0; i < childrenOrgList.size(); i++) {
                JSONObject orgItem = childrenOrgList.getJSONObject(i);
                String adCode = "0";

                //如果IsFenYuan为true，则从childrenOrgList中找到其父节点
                if (orgItem.getBoolean("IsFenYuan")) {
                    for (int j = 0; j < childrenOrgList.size(); j++) {
                        JSONObject parentItem = childrenOrgList.getJSONObject(j);
                        if (parentItem.getString("ObjectId").equals(orgItem.getString("ParentOrg"))) {
                            adCode = parentItem.getString("ObjectId");
                        }
                    }
                    CityLevel = 3;
                } else {
                    CityLevel = 2;
                }

                // 字段映射 ClientName -> AreaName AdCode -> AreaCode CityLevel默认为4 Lng->Lng Lat->Lat
                // 新创建一个对象
                JSONObject newOrgItem = new JSONObject();
                newOrgItem.put("AreaName", orgItem.getString("ClientName"));
                newOrgItem.put("AreaCode", orgItem.getString("ObjectId"));
                newOrgItem.put("ParentCode", adCode);
                newOrgItem.put("CityLevel", CityLevel);
                newOrgItem.put("Lng", orgItem.getDouble("Lng"));
                newOrgItem.put("Lat", orgItem.getDouble("Lat"));

                // 添加到映射列表中
                mappedOrgList.add(newOrgItem);
            }

            // 存储所有需要添加到树中的节点
            List<JSONObject> allNodes = new ArrayList<>();

            // 添加全部数据
            allNodes.addAll(mappedOrgList);
            //添加一条跟数据
            JSONObject root = new JSONObject();
            root.put("AreaName", "所有医院");
            root.put("AreaCode", "0");
            root.put("ParentCode", null);
            root.put("CityLevel", 1);
            allNodes.add(root);

            // 去重，避免重复节点
            Map<String, JSONObject> uniqueNodes = new HashMap<>();
            for (JSONObject node : allNodes) {
                uniqueNodes.put(node.getString("AreaCode"), node);
            }

            // 创建新的JSONArray
            JSONArray resultArray = new JSONArray();
            resultArray.addAll(uniqueNodes.values());

            // 将平面数组转换为树形结构，使用BizHandler中的方法
            JSONObject rootNode = BizHandler.buildRegionTree(resultArray, parentCode);
            return Result.success(rootNode, "查询成功");

        } catch (Exception e) {
            log.error("列表失败: {}", e.getMessage());
            return Result.error(ResultCode.SYSTEM_ERROR, "失败: " + e.getMessage());
        }
    }
    
    @Override
    public Result<JSONObject> getPowerConfig() {
        try {
            // 查询系统配置信息
            JSONArray bizObjectArray = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_POWER_CONFIG, new HashMap<>(), "ObjectId,AdminRoles,ChildrenOrgRoles");
            
            if (bizObjectArray == null || bizObjectArray.isEmpty()) {
                return Result.error("未找到系统配置信息");
            }
            
            // 只返回第一条记录
            return Result.success(bizObjectArray.getJSONObject(0), "获取系统配置成功");
        } catch (Exception e) {
            log.error("获取系统配置失败: {}", e.getMessage());
            return Result.error(ResultCode.SYSTEM_ERROR, "获取系统配置失败: " + e.getMessage());
        }
    }

    @Override
    public Result<JSONObject> getStationConfig(String areaCode) {
        try {
            // 查询系统配置信息
            JSONArray bizObjectArray = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_STATION_CONFIG, new HashMap<>());

            if (bizObjectArray == null || bizObjectArray.isEmpty()) {
                return Result.error("未找到单站配置信息");
            }

            JSONObject config = null;

            //如果powerCode为admin，则过滤类型为总公司的配置，否则查询指定区域
            if (StrUtil.isBlank(areaCode)) {
                for (int i = 0; i < bizObjectArray.size(); i++) {
                    JSONObject obj = bizObjectArray.getJSONObject(i);
                    if (obj.containsKey("ConfigType") && obj.getString("ConfigType").equals("总公司")) {
                        config = obj;
                        break;
                    }
                }
            } else {
                for (int i = 0; i < bizObjectArray.size(); i++) {
                    JSONObject obj = bizObjectArray.getJSONObject(i);
                    if (obj.containsKey("OrgId") && obj.getString("OrgId").equals(areaCode)) {
                        config = obj;
                        break;
                    }
                }
                if (config == null) {
                    for (int i = 0; i < bizObjectArray.size(); i++) {
                        JSONObject obj = bizObjectArray.getJSONObject(i);
                        if (obj.containsKey("ConfigType") && obj.getString("ConfigType").equals("总公司")) {
                            config = obj;
                            break;
                        }
                    }
                }
            }

            // 只返回第一条记录
            return Result.success(config, "获取单站配置成功");
        } catch (Exception e) {
            log.error("获取单站配置失败: {}", e.getMessage());
            return Result.error(ResultCode.SYSTEM_ERROR, "获取单站配置失败: " + e.getMessage());
        }
    }

    @Override
    public Result<JSONArray> getHomeCameraList(String powerCode, String orgObjectId) {
        try {
            // 查询主监控点信息
            JSONArray cameraArray = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_HOME_CAMERA, new HashMap<>());

            if (cameraArray == null || cameraArray.isEmpty()) {
                return Result.success(new JSONArray(), "未找到主监控点信息");
            }

            // 客户信息列表
            String returnItems = "ObjectId, Name, ClientName, Address, Location";
            Map<String, Object> queryParams = new HashMap<>();
            JSONArray userObjectArray = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_CHILDREN_ORG, queryParams, returnItems);

            // 监控点信息列表
            JSONArray channelObjectArray = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_CHANNEL_INFO, queryParams);

            JSONArray resultList = new JSONArray();
            
            // 根据权限类型过滤数据
            for (int i = 0; i < cameraArray.size(); i++) {
                JSONObject cameraObj = cameraArray.getJSONObject(i);
                
                // 权限过滤条件
                boolean shouldInclude = Objects.equals(powerCode, "admin") 
                    ? cameraObj.containsKey("ConfigType") && cameraObj.getString("ConfigType").equals("总公司")
                    : cameraObj.containsKey("OrgId") && cameraObj.getString("OrgId").equals(orgObjectId);
                
                if (shouldInclude) {
                    // 丰富摄像头对象信息
                    enrichCameraInfo(cameraObj, userObjectArray, channelObjectArray);
                    resultList.add(cameraObj);
                }
            }
            
            return Result.success(resultList, "获取主监控点配置成功");
        } catch (Exception e) {
            log.error("获取主监控点配置失败: {}", e.getMessage());
            return Result.error(ResultCode.SYSTEM_ERROR, "获取主监控点配置失败: " + e.getMessage());
        }
    }

    @Override
    public Result<JSONObject> addHomeCamera(HomeCameraDomain vo) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("ConfigType", vo.getConfigType());
        jsonObject.put("OrgId", vo.getOrgId());
        jsonObject.put("ChannelId", vo.getChannelId());
        //判断是否已添加
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("ConfigType", vo.getConfigType());
        queryParams.put("OrgId", vo.getOrgId());
        queryParams.put("ChannelId", vo.getChannelId());
        JSONArray listArray = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_HOME_CAMERA, queryParams);
        if (listArray != null && listArray.size() > 0) {
            return Result.error("该主监控点已添加");
        }
        JSONObject res = h3yunOperate.CreateBizObject(H3yunApiConstants.SCHEMA_HOME_CAMERA, jsonObject);
        return Result.success(res);
    }

    @Override
    public Result<JSONArray> getEventList(String areaCode) {
        try {
            // 客户信息列表
            Map<String, Object> queryParams = new HashMap<>();
            queryParams.put("OrgId", areaCode);
            JSONArray resultList = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_ALARM_EVENT, queryParams, 0,20);
            if (resultList == null || resultList.isEmpty()) {
                return Result.success(new JSONArray());
            }
            return Result.success(resultList, "ok");
        } catch (Exception e) {
            log.error("err: {}", e.getMessage());
            return Result.error(ResultCode.SYSTEM_ERROR, "err: " + e.getMessage());
        }
    }

    @Override
    public Result<JSONArray> getYesterdayW00000Count() {
        JSONObject params = new JSONObject();
        JSONArray bizObject = h3yunOperate.CustomInvokeArray("EventStatistics", "statYesterdayW00000Count", params);
        return Result.success(bizObject, "ok");
    }

    @Override
    public Result<String> addYesterdayW00000Count(JSONArray list) {
        if (list.isEmpty()) {
            return Result.error("列表为空");
        }
        for (int i = 0; i < list.size(); i++) {
            JSONObject obj = list.getJSONObject(i);
            //判断是否已存在
            Map<String, Object> queryParams = new HashMap<>();
            queryParams.put("Org", obj.getString("org_id"));
            queryParams.put("ItemName", "处理水量");
            queryParams.put("StatTime", obj.getString("date"));
            JSONArray listArray = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_RUN_DATA_RECORDS, queryParams);
            if (listArray != null && listArray.size() > 0) {
                log.info("已存在,跳过: {}", obj.getString("org_id"));
                continue;
            }
            JSONObject bizObject = new JSONObject();
            bizObject.put("Org", obj.getString("org_id"));
            bizObject.put("ItemName", "处理水量");
            bizObject.put("ItemValue", obj.getDoubleValue("w00000_cou"));
            bizObject.put("Unit", "m³");
            bizObject.put("StatTime", obj.getString("date"));
            bizObject.put("DataSource", "设备上报");
            bizObject.put("mn", obj.getString("mn_no"));
            bizObject.put("F0000001", getDingTalkDept(obj.getString("mn_no"))); //获取钉钉部门
            h3yunOperate.CreateBizObject(H3yunApiConstants.SCHEMA_RUN_DATA_RECORDS, bizObject);
        }
        return Result.success("保存成功");
    }

    //获取钉钉部门
    private String getDingTalkDept(String mn) {
        JSONArray sensorDeviceList = dataCacheService.getSensorDevice();
        String orgDingDingDept = null;
        //遍历,根据DeviceCode字段和MN字段匹配
        for (int i = 0; i < sensorDeviceList.size(); i++) {
            JSONObject sensorDevice = sensorDeviceList.getJSONObject(i);
            if (sensorDevice.getString("DeviceCode").equals(mn)) {
                orgDingDingDept = sensorDevice.getString("OrgDingDingDept");
            }
        }
        return orgDingDingDept;
    }

    @Override
    public Result<String> deleteHomeCamera(String objectId) {
        h3yunOperate.RemoveBizObject(H3yunApiConstants.SCHEMA_HOME_CAMERA, objectId);
        return Result.success("ok");
    }

    /**
     * 丰富摄像头对象的信息，添加组织名称和通道名称
     * @param cameraObj 摄像头对象
     * @param userObjectArray 用户/组织对象数组
     * @param channelObjectArray 通道对象数组
     */
    private void enrichCameraInfo(JSONObject cameraObj, JSONArray userObjectArray, JSONArray channelObjectArray) {
        // 添加组织名称
        if (cameraObj.containsKey("OrgId")) {
            String orgId = cameraObj.getString("OrgId");
            findAndProcessObject(userObjectArray, "ObjectId", orgId, userObj -> {
                cameraObj.put("OrgName", userObj.getString("ClientName"));
            });
        }
        
        // 添加通道名称和通道所属组织信息
        if (cameraObj.containsKey("ChannelId")) {
            String channelId = cameraObj.getString("ChannelId");
            findAndProcessObject(channelObjectArray, "ObjectId", channelId, channelObj -> {
                cameraObj.put("ChannelName", channelObj.getString("ChannelName"));
                //设置通道的所属单位
                if (channelObj.containsKey("OrgId")) {
                    String channelOrgId = channelObj.getString("OrgId");
                    cameraObj.put("OrgId", channelOrgId);
                    
                    //查询并设置通道的所属组织
                    findAndProcessObject(userObjectArray, "ObjectId", channelOrgId, userObj -> {
                        cameraObj.put("ChannelOrgName", userObj.getString("ClientName"));
                    });
                }
            });
        }
    }
    
    /**
     * 在JSONArray中查找匹配的对象并处理
     * @param array 要搜索的JSONArray
     * @param fieldName 匹配的字段名
     * @param fieldValue 匹配的字段值
     * @param processor 处理器函数，用于处理找到的对象
     */
    private void findAndProcessObject(JSONArray array, String fieldName, String fieldValue, java.util.function.Consumer<JSONObject> processor) {
        if (array == null || fieldValue == null) {
            return;
        }
        
        for (int i = 0; i < array.size(); i++) {
            JSONObject obj = array.getJSONObject(i);
            if (obj.containsKey(fieldName) && fieldValue.equals(obj.getString(fieldName))) {
                processor.accept(obj);
                break;  // 找到匹配项后立即退出循环
            }
        }
    }
    
    /**
     * 递归查找父级编码路径
     * @param parentCode 父级编码
     * @param bizObjectArray 业务对象数组
     * @return 父级路径列表
     */
    private List<JSONObject> findParentCodePath(String parentCode, JSONArray bizObjectArray) {
        List<JSONObject> result = new ArrayList<>();
        if (parentCode == null || parentCode.isEmpty()) {
            return result;
        }
        
        // 在现有数组中查找父级
        for (int i = 0; i < bizObjectArray.size(); i++) {
            JSONObject node = bizObjectArray.getJSONObject(i);
            if (parentCode.equals(node.getString("AreaCode"))) {
                // 找到匹配的节点，添加到结果中
                result.add(node);
                // 继续查找上级节点
                String grandParentCode = node.getString("ParentCode");
                if (grandParentCode != null && !grandParentCode.isEmpty()) {
                    result.addAll(findParentCodePath(grandParentCode, bizObjectArray));
                }
                return result;
            }
        }
        
        return result;
    }
    
    @Override
    public Result<JSONArray> queryChannelInfo(Map<String, Object> queryParams, String powerCode, String orgObjectId) {
        JSONArray bizObjectArray = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_CHANNEL_INFO, queryParams);
        if (bizObjectArray == null || bizObjectArray.isEmpty()) {
            return Result.success(new JSONArray());
        }
        //如果powerCode为admin，则返回全部数据，否则查询指定区域
        JSONArray list = new JSONArray();
        if (Objects.equals(powerCode, "admin")) {
            list.addAll(bizObjectArray);
        } else {
            for (int i = 0; i < bizObjectArray.size(); i++) {
                JSONObject obj = bizObjectArray.getJSONObject(i);
                if (obj.containsKey("OrgId") && obj.getString("OrgId").equals(orgObjectId)) {
                    list.add(obj);
                }
            }
        }

        // 客户信息列表
        String returnItems = "ObjectId, Name, ClientName, Address, Location";
        Map<String, Object> queryParams1 = new HashMap<>();
        JSONArray userObjectArray = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_CHILDREN_ORG, queryParams1, returnItems);

        for (int i = 0; i < list.size(); i++) {
            JSONObject obj = list.getJSONObject(i);
            String orgId = obj.getString("OrgId");
            findAndProcessObject(userObjectArray, "ObjectId", orgId, userObj -> {
                obj.put("OrgName", userObj.getString("ClientName"));
            });
        }

        return Result.success(list, "查询通道信息成功");
    }

    @Override
    public Result<String> updateHomeCameraOrder(List<UpdateCameraOrderDomain> list) {
        for (UpdateCameraOrderDomain info : list) {
            JSONObject bizObject = new JSONObject();
            bizObject.put("sortVal", info.getSortVal());
            h3yunOperate.UpdateBizObject(H3yunApiConstants.SCHEMA_HOME_CAMERA, info.getObjectId(), bizObject);
        }
        return Result.success("ok", "ok");
    }

    @Override
    public Result<JSONArray> getHomeChannelList(String powerCode, String orgObjectId) {
        //通道列表
        JSONArray bizObjectArray = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_CHANNEL_INFO, new HashMap<>());

        //传感器设备
        JSONArray sensorDevice = dataCacheService.getSensorDevice();

        // 客户信息列表
        JSONArray userObjectArray = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_CHILDREN_ORG, new HashMap<>(), "ObjectId, adcode");

        Map<String, Object> queryParams = new HashMap<>();
        if (StrUtil.isBlank(orgObjectId)) {
            queryParams.put("ConfigType", "总公司");
        } else {
            queryParams.put("OrgId", orgObjectId);
        }
        // 查询主监控点信息
        JSONArray cameraArray = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_HOME_CAMERA, queryParams);
        if (cameraArray == null || cameraArray.isEmpty()) {
            return Result.success(new JSONArray(), "未找到主监控点信息");
        }
        List<String> cameraChannelIds = new ArrayList<>();
        for (int i = 0; i < cameraArray.size(); i++) {
            JSONObject obj = cameraArray.getJSONObject(i);
            cameraChannelIds.add(obj.getString("ChannelId"));
        }

        JSONArray list = new JSONArray();
        //从bizObjectArray中过滤出cameraArray中包含的ChannelId的item
        for (int i = 0; i < bizObjectArray.size(); i++) {
            JSONObject obj = bizObjectArray.getJSONObject(i);
            if (cameraChannelIds.contains(obj.getString("ObjectId"))) {
                //增加SensorDeviceMN字段
                JSONObject sensorObj = getSensorDeviceObj(sensorDevice, obj.getString("ObjectId"));
                obj.put("SensorDeviceMN", sensorObj != null ? sensorObj.getString("DeviceCode") : null);
                //增加adcode字段
                findAndProcessObject(userObjectArray, "ObjectId", obj.getString("OrgId"), userObj -> {
                    obj.put("adcode", userObj.getString("adcode"));
                });
                //增加sortVal字段
                findAndProcessObject(cameraArray, "ChannelId", obj.getString("ObjectId"), userObj -> {
                    obj.put("sortVal", userObj.getIntValue("sortVal"));
                });
                list.add(obj);
            }
        }

        return Result.success(list, "查询主监控点通道列表成功");
    }

    @Override
    public Result<JSONArray> getCheckList(String powerCode, String unitId) {
        Map<String, Object> queryParams = new HashMap<>();
        if (!Objects.equals(powerCode, "admin")) {
            queryParams.put("F0000011", unitId);
        }
        JSONArray list = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_CHECK_LIST, queryParams);
        return Result.success(list, "ok");
    }

    private JSONObject getSensorDeviceObj(JSONArray sensorDevice, String ChannelId) {
        //根据监控点ID获取传感器设备信息
        JSONObject sensorDeviceObj = null;
        for (int i = 0; i < sensorDevice.size(); i++) {
            JSONObject device = sensorDevice.getJSONObject(i);
            if (device.getString("ChannelId").equals(ChannelId)) {
                sensorDeviceObj = device;
                break;
            }
        }
        return sensorDeviceObj;
    }

    @Override
    public Result<JSONObject> queryAndBatchDelSensorEventData(String cn) {
        Map<String, Object> queryParams = new HashMap<>();
        if (cn != null && !cn.isEmpty()) {
            queryParams.put("CN", cn);
        }
        JSONArray bizObjectArray = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_SENSOR_EVENT_DATA, queryParams, "ObjectId");
        if (bizObjectArray == null || bizObjectArray.isEmpty()) {
            return Result.error(ResultCode.PARAM_ERROR, "未找到指定CN的传感器事件数据");
        }
        List<String> objectIds = new ArrayList<>();
        for (int i = 0; i < bizObjectArray.size(); i++) {
            JSONObject jsonObject = bizObjectArray.getJSONObject(i);
            objectIds.add(jsonObject.getString("ObjectId"));
        }
        log.info("开始批量删除传感器事件数据, 对象ID数量: {}", objectIds.size());
        
        if (objectIds.isEmpty()) {
            return Result.error(ResultCode.PARAM_ERROR, "对象ID列表不能为空");
        }
        
        JSONObject result = h3yunOperate.RemoveBizObjects(H3yunApiConstants.SCHEMA_SENSOR_EVENT_DATA, objectIds);
        return Result.success(result, "删除传感器事件数据成功");
    }
    
    @Override
    public Result<JSONArray> queryAllDeviceInfo(Map<String, Object> queryParams) {
        JSONArray bizObjectArray = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_DEVICE_INFO, queryParams);
        return Result.success(bizObjectArray, "查询所有设备信息成功，总记录数: " + bizObjectArray.size());
    }

    @Override
    public Result<JSONArray> queryAllChannelInfo(Map<String, Object> queryParams) {
        JSONArray bizObjectArray = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_CHANNEL_INFO, queryParams);
        return Result.success(bizObjectArray, "查询所有通道信息成功，总记录数: " + bizObjectArray.size());
    }

    @Override
    public Result<JSONArray> getWorkOrder(String OrgId) {
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("OrgId", OrgId);
        JSONArray listArray = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_WORK_ORDER, queryParams);
        //判空
        if (listArray == null || listArray.isEmpty()) {
            return Result.success(new JSONArray());
        }
        return Result.success(listArray);
    }

    @Override
    public Result<JSONArray> getSensorDeviceList(String powerCode, String OrgId) {
        Map<String, Object> queryParams = new HashMap<>();
        if (!Objects.equals(powerCode, "admin")) {
            queryParams.put("OrgId", OrgId);
        }
        JSONArray listArray = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_SENSOR_DEVICE, queryParams);
        return Result.success(listArray);
    }

    @Override
    public Result<JSONArray> getEventPicTempList() {
        JSONArray listArray = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_EVENT_LIST_PIC_TEMP, new HashMap<>(), true);
        return Result.success(listArray);
    }

    @Override
    public void queryEventTempPicAndDelete() {
        //打印开始时间
        log.info("======开始删除临时图片，时间：{}，======", DateUtil.now());
        Result<JSONArray> res = this.getEventPicTempList();
        JSONArray list = res.getData();
        //遍历删除文件
        if (list == null || list.isEmpty()) {
            log.info("没有需要删除的图片");
            return;
        }
        log.info("需要删除的图片数量：{}", list.size());
        int okCount = 0;
        int errorCount = 0;
        for (int i = 0; i < list.size(); i++) {
            JSONObject item = list.getJSONObject(i);
            String objectId = item.getString("ObjectId");
            String PicUrl1 = item.getString("PicUrl1");
            String PicUrl2 = item.getString("PicUrl2");
            if (StrUtil.isBlank(PicUrl1) || StrUtil.isBlank(PicUrl2)) {
                log.info("图片地址为空，跳过删除");
                //删除【事件列表删除图片临时表】数据
                h3yunOperate.RemoveBizObject(H3yunApiConstants.SCHEMA_EVENT_LIST_PIC_TEMP, objectId);
                continue;
            }
            //格式：http://water.mtzxpt.cn/image/download?url=e1eb3aa3-fab1-4e2c-b359-2e065b164d3c_thumbnail.jpg
            //解析url的值
            String path1 = PicUrl1.substring(PicUrl1.indexOf("url=") + 4);
            String path2 = PicUrl2.substring(PicUrl2.indexOf("url=") + 4);
            if (StrUtil.isBlank(path1) || StrUtil.isBlank(path2)) {
                log.info("图片地址为空，跳过删除");
                continue;
            }
            try {
                //删除文件
                boolean isOk = commonService.deleteFile(path1);
                if (!isOk) {
                    //删除【事件列表删除图片临时表】数据
                    h3yunOperate.RemoveBizObject(H3yunApiConstants.SCHEMA_EVENT_LIST_PIC_TEMP, objectId);
                    continue;
                }
                commonService.deleteFile(path2);
                okCount++;
            } catch (Exception e) {
                log.info("删除图片失败：{}", e.getMessage());
                errorCount++;
            } finally {
                //删除【事件列表删除图片临时表】数据
                h3yunOperate.RemoveBizObject(H3yunApiConstants.SCHEMA_EVENT_LIST_PIC_TEMP, objectId);
            }
        }
        log.info("删除图片完成，成功删除{}张，失败{}张", okCount, errorCount);
        log.info("======结束删除临时图片，时间：{}，======", DateUtil.now());
    }

    @Override
    public void queryAndBatchDelEventPicTest() {
        JSONArray list = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_ALARM_EVENT, new HashMap<>(), "*", true);
        if (list == null || list.isEmpty()) {
            return;
        }
        //排除的数据
        List<String> excludeList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            JSONObject item = list.getJSONObject(i);
            String ThumbnailUrl = item.getString("ThumbnailUrl");
            String AlarmPic = item.getString("AlarmPic");
            if (StrUtil.isBlank(ThumbnailUrl) || StrUtil.isBlank(AlarmPic)) {
                continue;
            }
            ThumbnailUrl = ThumbnailUrl.substring(ThumbnailUrl.indexOf("url=") + 4);
            AlarmPic = AlarmPic.substring(AlarmPic.indexOf("url=") + 4);
            excludeList.add(ThumbnailUrl);
            excludeList.add(AlarmPic);
        }
        List<String> allPathList = commonService.listAllImageFiles();
        //排除的数据不删除
        for (String path : allPathList) {
            if (!excludeList.contains(path)) {
                commonService.deleteFile(path);
            }
        }
    }

    @Override
    public Result<JSONArray> getCommonConfig() {
        JSONArray bizObjectArray = h3yunOperate.LoadBizObjects(H3yunApiConstants.SCHEMA_COMMON_CONFIG, new HashMap<>(), "code,title,value");
        return Result.success(bizObjectArray, "成功");
    }
}